package com.njtoyo.taxi.admin.library.common;

import cn.hutool.extra.servlet.ServletUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.google.common.base.Strings;
import com.njtoyo.taxi.admin.library.Const;
import com.njtoyo.taxi.admin.mapper.secondary.entity.OperationRecord;
import com.njtoyo.taxi.admin.mapper.secondary.mapper.OperationRecordMapper;
import com.njtoyo.taxi.admin.rest.wrapper.Identity;
import com.njtoyo.taxi.admin.security.TokenVerifier;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Slf4j
@Service
@DS(Const.SECONDARY_DS)
public class OperationRecordHelper {

    @Autowired
    private TokenVerifier verifyToken;

    @Autowired
    private OperationRecordMapper operationRecordMapper;

    public void addBusinessLog(String describe) {
        this.addLog("business", describe);
    }

    public void addCarAdvLog(String describe) {
        this.addLog("car_adv", describe);
    }

    private void addLog(String module, String describe) {
        log.info("操作记录 {} {}", module, describe);
        try {
            OperationRecord operationRecord = new OperationRecord();
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String clientIP = ServletUtil.getClientIP(request);
            operationRecord.setIp(clientIP).setModule(module).setDescribe(describe).setUserId(0L);
            String token = request.getHeader("Authorization");

            if (Objects.nonNull(token)) {
                token = verifyAccessToken(token);
                Identity identity = verifyToken.verifyIdentityToken(token);
                if (Objects.nonNull(identity)) {
                    operationRecord.setUserId(identity.getAdminUser().getId().longValue());
                }
            }
            operationRecordMapper.insert(operationRecord);
        } catch (Exception e) {
            log.info("操作日志保存错误 {}", e.getMessage());
        }
    }

    private String verifyAccessToken(String accessToken) {
        int firstSpaceIndex = accessToken.indexOf(" ");

        if (firstSpaceIndex == -1) {
            return null;
        }

        String authMethod = accessToken.substring(0, firstSpaceIndex).trim();
        String token = accessToken.substring(firstSpaceIndex).trim();

        if (!authMethod.equalsIgnoreCase("Bearer") || Strings.isNullOrEmpty(token)) {
            return null;
        }
        return token;
    }
}
